package org.lex.io.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Zip {
	private Logger log = LoggerFactory.getLogger(Zip.class);
	private File folder = null;
	private File zipFile = null;

	public Zip(File folder, File zipFile) {
		this.folder = folder;
		this.zipFile = zipFile;
	}

	public void zip() throws IOException {
		log.info("Zip folder=" + folder);
		File[] files = folder.listFiles();
		log.info(files.length + " files found");

		log.info("Zip output file=" + zipFile);
		if (false == zipFile.exists() || false == zipFile.isFile()) {
			boolean result = zipFile.createNewFile();
			log.info("Output file=" + zipFile + " not exists, create success? " + result);
		}

		ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
		zip.setLevel(9);
		for (File file : files) {
			log.info("Current file=" + file);
			ZipEntry entry = new ZipEntry(file.getName());
			zip.putNextEntry(entry);

			InputStream in = new FileInputStream(file);
			IOUtils.copy(in, zip);
			in.close();
			log.info("Write " + file.length() + " bytes to zip file");

			zip.flush();
			zip.closeEntry();
		}
		zip.close();
		log.info("Zip finished, output bytes=" + zipFile.length());
	}

	public static void main(String[] args) throws Exception {
		File dir = new File("D:\\_liuex\\export\\zip");
		File out = new File(dir, "out.zip");

		Zip zip = new Zip(dir, out);
		zip.zip();
	}
}
